import pandas as pd
import numpy as np

data = {
    "日期": pd.date_range("2024-01-01", periods=10, freq="D"),
    "商品": ["牛奶", "面包", "鸡蛋", "牛奶", "面包", "鸡蛋", "牛奶", "面包", "鸡蛋", "牛奶"],
    "单价": [4.5, 3.0, 0.8, 4.8, 3.2, np.nan, 4.6, 3.1, 0.9, 4.7],
    "销量": [50, 80, 200, 45, 90, 180, np.nan, 95, 190, 60]
}
df = pd.DataFrame(data)

#基本操作
print(df.head())
print(df.dtypes)
print(df.isnull().sum())
df['销售额'] = df['单价'] * df['销量']

#数据清洗
df['单价'].fillna(df['单价'].mean(), inplace=True)
df['销量'].fillna(df['销量'].mean(), inplace=True)
print(df.isnull().sum())

#数据筛选与计算
milk = df[df['商品'] == '牛奶']
print(f"牛奶总销量: {milk['销量'].sum()}")
print(f"牛奶总销售额: {milk['销售额'].sum()}")
max_sale = df.loc[df['销售额'].idxmax()]
print("最高销售额记录:")
print(max_sale)

#数据聚合
by_product = df.groupby('商品').agg({'单价':'mean', '销量':'sum', '销售额':'sum'})
by_date = df.groupby('日期')['销售额'].sum()
print(by_product)
print(by_date)